<template>
  <!-- 公司设置 -->
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                :disabled="!checkPermission('addRole')"
                @click="addRole"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="roleList">
              <el-table-column label="序号" width="120" type="index">
                <template #default="{$index}">
                  {{ (page.page - 1) * page.pagesize + ($index + 1) }}
                </template>
              </el-table-column>
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <!-- 作用域插槽 -->
                <template #default="{row}">
                  <el-button size="small" type="success" :disabled="!checkPermission('assignPermission')" @click="assignPermission(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" :disabled="!checkPermission('editRole')" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                layout="prev,pager,next"
                :total="page.total"
                :page-size="page.pagesize"
                @current-change="currentChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增和编辑弹出框 -->
      <el-dialog title="新增角色" :visible="showDialog" @close="btnCancel">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
        <el-tree
          ref="permTree"
          :data="permissionList"
          :props="{ label: 'name' }"
          :show-checkbox="true"
          :check-strictly="true"
          node-key="id"
        />
        <!-- 确定 取消 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
            <el-button size="small" @click="btnPermCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getCompanyInfo, getRoleList, delRole, getRoleDetail, editRole, assignPerm } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { listToTreeData } from '@/utils'
import { mapGetters } from 'vuex'
export default {
  data() {
    const checkNameRepeat = async(rule, val, callback) => {
      const { rows } = await getRoleList({ page: 1, pagesize: this.page.total })
      if (rows.some(item => item.name === val && item.id !== this.roleForm.id)) {
        callback(new Error('名字不能重复'))
      } else {
        callback()
      }
    }
    return {
      // 当前点击员工的id
      roleId: '',
      // 编辑权限弹窗
      showPermDialog: false,
      // 获取全部权限列表
      permissionList: [],
      // 当前被点击的角色已选中的权限
      checkedPermissionList: [],
      formData: {},
      page: {
        page: 1,
        pagesize: 2,
        total: 0 // 总条数
      },
      roleList: [],
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          { trigger: 'blur', validator: checkNameRepeat }
        ],
        description: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['companyId']),
    dialogTitle() {
      return this.roleForm.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getCompanyInfo()
    this.getRoleList()
  },
  methods: {
    // 获取公司信息
    async getCompanyInfo() {
      this.formData = await getCompanyInfo(this.companyId)
      // console.log(this.formData)
    },
    // 获取员工列表
    async getRoleList() {
      const { rows, total } = await getRoleList(this.page)
      this.roleList = rows
      console.log(this.roleList)
      this.page.total = total
    },
    // 监听分页切换（分页切换改变页面内容）
    currentChange(newPage) {
      // 参数就是我们当前点击的页码
      this.page.page = newPage
      // 发送请求重新获取数据
      this.getRoleList()
    },
    async delRole(id) {
      try {
        // 校验
        await this.$confirm('确认删除？')
        // 发请求
        await delRole(id)
        // 更新页面（也可能存在是这一页的最后一条，删完要换页）
        if (this.roleList.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        this.getRoleList()
        // 提示
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    async editRole(id) {
      // 点击编辑回显数据
      this.roleForm = await getRoleDetail(id)
      this.showDialog = true
    },
    addRole() {
      this.showDialog = true
    },
    // 点击确定
    async btnOK() {
      // 校验表单
      await this.$refs.roleForm.validate()
      // 发请求
      await editRole(this.roleForm)
      // 提示用户
      this.$message.success('操作成功')
      // 更新页面
      this.getRoleList()
      // 关闭弹窗
      this.showDialog = false
    },
    // 点击取消
    btnCancel() {
      // 1. 清理表单
      this.roleForm = {
        name: '',
        description: ''
      }
      // 2. 清理校验
      this.$refs.roleForm.resetFields()
      // 3. 关闭弹窗
      this.showDialog = false
    },
    // 分配权限
    async assignPermission(id) {
      // 获取全部权限列表
      this.permissionList = listToTreeData(await getPermissionList(), '0')
      // 获取当前角色权限
      const { permIds } = await getRoleDetail(id)
      this.checkedPermissionList = permIds
      // 记下id
      this.roleId = id
      // 弹窗
      this.showPermDialog = true
      // 页面加载完成渲染页面
      this.$nextTick(() => {
        this.$refs.permTree.setCheckedKeys(this.checkedPermissionList)
      })
    },
    // 点击确定编辑
    async btnPermOK() {
      // 发请求
      await assignPerm({
        id: this.roleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      // 提示用户
      this.$message.success('分配权限成功')
      // 关闭弹窗
      this.showPermDialog = false
    },
    btnPermCancel() {
      // 清空数据
      this.$refs.permTree.setCheckedKeys([])
      // 关闭弹窗
      this.showPermDialog = false
    }
    // 控制权限功能(挂到全局就不用在这里单独写了)
    // checkPermission(point) {
    //   // 判断当前登陆的账号有没有存有这个权限
    //   return this.$store.state.user.userInfo.roles.points.includes(point)
    // }
  }
}
</script>

<style>

</style>
